<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Article;
use App\Models\Category;
use App\Models\Config;
use App\Models\Tag;
use App\Models\ArticleTag;
use App\Http\Requests\Article\Store;
use Illuminate\Support\Facades\Storage;
use DB;
class ArticleController extends Controller
{
    //
    public function index(Request $request, Article $article)
    {
        $wd = trim($request->input('wd', ''));
        $article = Article::with('category')
            ->orderBy('created_at', 'desc')
            ->when($wd !== '', function ($query) use ($wd) {
                return $query->whereIn('id', Article::getIdsGivenSearchWord($wd));
            })
            ->withTrashed()
            ->paginate(15);
        $assign = compact('article');
        return view('admin.article.index',$assign);
    }
    public function create()
    {
         $category = Category::all();
        $tag      = Tag::all();
        $author   = Config::where('name', 'bjyblog.author')->value('value');
        $assign   = compact('category', 'tag', 'author');

        return view('admin.article.create', $assign);
    }
    public function uploadImage(Request $request)
    {
        $result = [
            'success' => 1,
            'message' => 'success',
            'url'     => '',
        ];

        foreach (config('bjyblog.upload_disks') as $disk) {
            $result['url'] = '/' . $request->file('editormd-image-file')->store('uploads/article/' . Date::now()->format('Ymd'), $disk);
        }

        return response()->json($result);
    }

    public function store(Store $request)
    {
        $article = $request->except('_token','q');
       
 
        if ($request->hasFile('cover')) {
         $file = $request->file('cover');
                $fil = $file->getClientOriginalName();
                $fil=time().strrchr($fil,'.');
                $url = $file->move("article/".date('Ymd'),$fil);            
                $article['cover'] = $url;    
        }
        if($article['description']=='')
        $article['description']=str_limit($article['markdown'],90);
        $tag_ids = $article['tag_ids'];
        unset($article['tag_ids']);
        $article = Article::create($article);
        $article->tags()->attach($tag_ids);
        
        return redirect(url('admin/article'));
    }
    public function edit($id)
    {
    	
        $category = Category::all();
        $tag      = Tag::all();
        $article  = Article::withTrashed()->find($id);
        $article->setAttribute('tag_ids', ArticleTag::where('article_id', $id)->pluck('tag_id')->toArray());

        return view('admin.article.edit', compact('article', 'category', 'tag'));
    }

    public function update(Store $request, $id)
    {
        $data = $request->except('_token','q');
        $article=Article::withTrashed()->find($id);
//dd($article);exit;
        // 上传封面图
        if ($request->hasFile('cover')) {
            
                $file = $request->file('cover');
                $fil = $file->getClientOriginalName();
                $fil=time().strrchr($fil,'.');
                $url = $file->move("article/".date('Ymd'),$fil);
                $data['cover'] = $url;
        }
if($data['description']==''){
        $data['description']=str_limit($data['markdown'],90);
        }
        $tag_ids = $data['tag_ids'];
        unset($data['tag_ids']);
        $article->update($data);
       
       $article->tags()->sync($tag_ids);
        return redirect()->back();
    }

    public function destroy($id)
    {
        Article::destroy($id);

        return redirect()->back();
    }

    public function restore($id)
    {
        Article::onlyTrashed()->find($id)->restore();

        return redirect()->back();
    }

    public function forceDelete($id)
    {
        Article::onlyTrashed()->find($id)->forceDelete();

        return redirect()->back();
    }
    public function replaceView()
    {
        return view('admin.article.replaceView');
    }

    public function replace(Request $request)
    {
        $search   = $request->input('search');
        $replace  = $request->input('replace');
        $articles = Article::select('id', 'title', 'keywords', 'description', 'markdown', 'html')
            ->where('title', 'like', "%$search%")
            ->orWhere('keywords', 'like', "%$search%")
            ->orWhere('description', 'like', "%$search%")
            ->orWhere('markdown', 'like', "%$search%")
            ->orWhere('html', 'like', "%$search%")
            ->get();

        foreach ($articles as $article) {
            DB::table('articles')->where('id', $article->id)->update([
                'title'       => str_replace($search, $replace, $article->title),
                'keywords'    => str_replace($search, $replace, $article->keywords),
                'description' => str_replace($search, $replace, $article->description),
                'markdown'    => str_replace($search, $replace, $article->markdown),
                'html'        => str_replace($search, $replace, $article->html),
            ]);
        }

        return redirect()->back()->withsuccess('替换完毕');
    }

}
